package de.bananenpelle.userscript.project;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.netbeans.api.project.Project;
import org.netbeans.spi.project.ProjectFactory;
import org.netbeans.spi.project.ProjectState;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;

@org.openide.util.lookup.ServiceProvider(service = ProjectFactory.class)
public class UserScriptProjectFactory implements ProjectFactory {

    public static final String PROJECT_DIR = "usproject";
    public static final String PROJECT_PROPFILE = "project.properties";

    //Specifies when a project is a project, i.e.,
    //if the project directory "texts" is present:
    @Override
    public boolean isProject(FileObject projectDirectory) {
        FileObject usprojectDirectory = projectDirectory.getFileObject(PROJECT_DIR);

        if (usprojectDirectory == null) {
            return false;
        }

        if (usprojectDirectory.getFileObject(PROJECT_PROPFILE) == null) {
            return false;
        }

        return true;
    }

    //Specifies when the project will be opened, i.e.,
    //if the project exists:
    @Override
    public Project loadProject(FileObject dir, ProjectState state) throws IOException {
        return isProject(dir) ? new UserScriptProject(dir, state) : null;
    }

    @Override
    public void saveProject(final Project project) throws IOException, ClassCastException {
        FileObject projectRoot = project.getProjectDirectory();
        if (projectRoot.getFileObject(PROJECT_DIR) == null) {
            throw new IOException("Project dir " + projectRoot.getPath() + " deleted," + " cannot save project");
        }

        ((UserScriptProject) project).getScriptsFolder(true);
        ((UserScriptProject) project).getResourcesFolder(true);

        String propsPath = PROJECT_DIR + "/" + PROJECT_PROPFILE;
        FileObject propertiesFile = projectRoot.getFileObject(propsPath);
        if (propertiesFile == null) {
            propertiesFile = projectRoot.createData(propsPath);
        }

        Properties properties = (Properties) project.getLookup().lookup(Properties.class);

        File f = FileUtil.toFile(propertiesFile);
        properties.store(new FileOutputStream(f), "NetBeans UserScript Project Properties");
    }
}